const express = require('express')
const app = express();
app.use(express.static('./public'));


const log4js = require('log4js')
log4js.configure({
  appenders: {
    file: {
      type: 'file',
      filename: 'app.log',
      layout: {
        type: 'pattern',
        pattern: '%r %p - %m'
      }
    }
  },
  categories: {
    default: {
      appenders: ['file'],
      level: 'debug'
    }
  }
})
const logger = log4js.getLogger();


const http = require('http');
const http_server = http.createServer(app);


//https://www.npmjs.com/package/socket.io
const socketIO = require('socket.io')
const io = socketIO(http_server); //Attaches socket.io to a server or port.

//bind socket.io with http_server
io.sockets.on('connection', (socket) => {
  socket.on('join', (roomId) => {
    socket.join(roomId); //如果是第一次 会帮你自动创建对应的room
    const room = io.sockets.adapter.rooms[roomId];
    const users_total_number = Object.keys(room.sockets).length;
    logger.log(`the number of user in room is ${users_total_number}`);

    socket.emit('joined', roomId, socket.id/*用户id*/);
    // socket.to(roomId).emit() //给房间内除自己之外
    // io.in(roomId).emit() //给目标房间的所有人
    //socket.broadcast.emit('joined',roomId,socket.id) //给当前节点除自己以外所有人
  });

  socket.on('leave', (roomId) => {
    const room = io.sockets.adapter.rooms[roomId];
    const users_total_number = Object.keys(room.sockets).length;
    socket.leave(roomId);
    logger.log(`the number of user in room is ${users_total_number - 1}`);

    socket.emit('joined', roomId, socket.id/*用户id*/);
    // socket.to(roomId).emit() //给房间内除自己之外
    // io.in(roomId).emit() //给目标房间的所有人
    //socket.broadcast.emit('joined',roomId,socket.id) //给当前节点除自己以外所有人
  });
});

http_server.listen(9191);


/*const https = require('https');
const fs = require('fs');
const options = {
  key: fs.readFileSync('./cert/xxx.xxx.xxx.key'),
  cert: fs.readFileSync('./cert/xxx.xxx.xxx.pem')
}
https_server = https.createServer(options,app);
https_server.listen(443)*/
